//
//  FQChatViewController.m
//  WeChat
//
//  Created by 方桥 on 16/5/17.
//  Copyright © 2016年 方桥. All rights reserved.
//

#import "FQChatViewController.h"

@interface FQChatViewController ()<NSFetchedResultsControllerDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSFetchedResultsController *_resultsContr;
}
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@end

@implementation FQChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //添加键盘的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(kbWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(kbWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    // Do any additional setup after loading the view.
    //加载数据库的聊天数据
    NSManagedObjectContext *context = [FQXmppTool sharedFQXmppTool].msgArchivingStorage.mainThreadManagedObjectContext;
    NSFetchRequest *requst = [[NSFetchRequest alloc]initWithEntityName:@"XMPPMessageArchiving_Message_CoreDataObject"];
    // 过滤 （当前登录用户 并且 好友的聊天消息）
    NSString *loginUserJid = [FQXmppTool sharedFQXmppTool].xmppStream.myJID.bare;
    
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"streamBareJidStr = %@ AND bareJidStr = %@",loginUserJid,self.friendJid.bare];
    requst.predicate = pre;
    // 设置时间排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
    requst.sortDescriptors = @[sort];
    
    _resultsContr = [[NSFetchedResultsController alloc]initWithFetchRequest:requst managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
    _resultsContr.delegate = self;
    NSError *error = nil;
    [_resultsContr performFetch:&error];
    FQLog(@"%@",error);
    FQLog(@"%@",_resultsContr.fetchedObjects);
    FQLog(@"%@",NSHomeDirectory());
}

-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
    //表格滚动到底部
    NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:_resultsContr.fetchedObjects.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
#pragma mark -tableView 的代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _resultsContr.fetchedObjects.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *Id = @"ChatCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Id];
    
    XMPPMessageArchiving_Message_CoreDataObject *msgObj = _resultsContr.fetchedObjects[indexPath.row];
    
    cell.textLabel.text = msgObj.body;
    
    return cell;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.textField endEditing:YES];
}
#pragma mark - 键盘的通知
-(void)kbWillShow:(NSNotification *)noti
{
    CGFloat kbHeight = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    _bottomConstraint.constant = kbHeight;
}

-(void)kbWillHide:(NSNotification *)noti
{
    _bottomConstraint.constant = 0;
}
#pragma mark - textField代理
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.friendJid];
    [message addBody:self.textField.text];
    [[FQXmppTool sharedFQXmppTool].xmppStream sendElement:message];
    //清空输入框
    self.textField.text = nil;
    return YES;
}
@end
